package com.leon.alishop.core.bof.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leon.alishop.core.bo.GoodsBo;
import com.leon.alishop.core.bof.GoodsBof;
import com.leon.alishop.core.bof.GoodsSkuBof;
import com.leon.alishop.core.config.ProviderConstant;
import com.leon.alishop.core.model.AttributesModel;
import com.leon.alishop.core.page.Page;
import com.leon.alishop.core.service.AttributesService;
import com.leon.alishop.core.vo.GoodsParams;
import com.leon.alishop.dao.GoodsAttrValDao;
import com.leon.alishop.dao.GoodsInfoDao;
import com.leon.alishop.dao.GoodsSkuDao;
import com.leon.alishop.model.AttrValInfo;
import com.leon.alishop.model.GoodsAttrVal;
import com.leon.alishop.model.GoodsInfo;
import com.leon.alishop.model.GoodsSku;
import com.leon.alishop.model.ProviderInfo;

@Service("goodsBof")
public class GoodsBofImpl implements GoodsBof{

	private static Logger log = LoggerFactory.getLogger(GoodsBofImpl.class);
	
	@Override
	public List<GoodsBo> showAllGoodsBoList(GoodsParams params,Page page) {
		if(page == null)
			page = new Page(100);
		Integer[] statusArr = null;
		if(params.getStatus()!= null){
			statusArr = new Integer[]{params.getStatus()};
		}
		int totalRows = goodsInfoDao.selectAllCount(params.getGoodsId(),params.getProviderId(), null,statusArr);
		page.setRecordCount(totalRows);
		if(totalRows == 0)
			return null;
		List<GoodsInfo> goodsInfoList = goodsInfoDao.selectAll(params.getGoodsId(),params.getProviderId(), null,statusArr, page.getFirstRow(), page.getPageSize());
		if(null == goodsInfoList || goodsInfoList.size()==0)
			return null;
		Map<Long,GoodsBo> goodsInfoMap = new LinkedHashMap<Long, GoodsBo>();
		List<Integer> providerIdList = new ArrayList<Integer>();
		GoodsBo gb = null;
		Map<String,String[]> imgUrlMap;
		List<String> minImgUrlList = null;
		for (GoodsInfo gi : goodsInfoList) {
			gb = new GoodsBo();
			BeanUtils.copyProperties(gi, gb);
			gb.setProviderInfo(ProviderConstant.getInstance().getProviderInfoById(gb.getProviderId()));
			goodsInfoMap.put(gi.getId(), gb);
			if((minImgUrlList = this.parseMinImgUrlMap(gb.getProviderGoodsImgInfo()))!= null
					&& minImgUrlList.size()>0){
				gb.setMinImgUrl(splitImgMinToBigUrl(minImgUrlList.get(0)));
			}
		}
		Long[] goodsInfoIds =  goodsInfoMap.keySet().toArray(new Long[goodsInfoMap.size()]);
		// SKU
		List<GoodsSku> skuList = goodsSkuDao.selectByGoodsIds(goodsInfoIds);
		if(null != skuList && skuList.size()>0){
			for (GoodsSku sku : skuList) {
				gb = goodsInfoMap.get(sku.getGoodsId());
				gb.addGoodsSku(sku);
			}
		}
		
		// ATTR
		List<GoodsAttrVal> gavList = goodsAttrValDao.selectByGoodsIds(goodsInfoIds);
		List<AttributesModel> attrModelList = new ArrayList<AttributesModel>();
		AttributesModel am,amTemp;
		AttrValInfo avi;
		if(gavList!= null && !gavList.isEmpty()){
			for (GoodsAttrVal _gav : gavList) {
				am = new AttributesModel();
				amTemp = attributesService.findAttributeById(_gav.getAttrId());
				if(amTemp==null){
					log.error("无效的Attributes Id:"+_gav.getAttrId());
					continue;
				}else if("颜色".equalsIgnoreCase(amTemp.getAttrName())
						|| "尺码".equalsIgnoreCase(amTemp.getAttrName())
						||"颜色分类".equalsIgnoreCase(amTemp.getAttrName())){
					continue;
				}else{
					BeanUtils.copyProperties(amTemp, am);
				}
				am.setAttrValList(null);
				avi = amTemp.getAttrValInfo(_gav.getAttrValId());
				if(avi==null){
					log.error("无效的Attributes Value Id:"+_gav.getAttrValId());
					continue;
				}else{
					am.addAttrVal(avi);
				}
				if(goodsInfoMap.containsKey(_gav.getGoodsId())){
					goodsInfoMap.get(_gav.getGoodsId()).addAttributesModel(am);
				}
			}
		}
		
		List<GoodsBo> ret = new ArrayList<GoodsBo>(goodsInfoMap.values());
		if(ret.size()>0){
			ProviderInfo pi;
			for (GoodsBo _gb : ret) {
				pi = _gb.getProviderInfo();
				_gb.setSkuTable(goodsSkuBof.parseGoodsSkuBoTable(pi,_gb.getSkuList()));
				_gb.setProviderGoodsName(this.parseHighlightGoodsName(_gb.getProviderGoodsName()));
			}
		}
		return ret;
	}

	
	private String parseHighlightGoodsName(String name){
		name = name.replaceFirst("春", "<span class=\"spring\">春</span>");
		name = name.replaceFirst("夏", "<span class=\"summer\">夏</span>");
		name = name.replaceFirst("秋", "<span class=\"autumn\">秋</span>");
		name = name.replaceFirst("冬", "<span class=\"winter\">冬</span>");
		return name;
	}
	
	private List<String> parseMinImgUrlMap(String imgInfoJsonStr){
		if(StringUtils.isBlank(imgInfoJsonStr))
			return Collections.emptyList();
		Map imgMap = null;
		imgMap = JSONObject.fromObject(imgInfoJsonStr);
		if(imgMap == null
				|| imgMap.size()==0)
			return Collections.emptyList();
		List<String> imgList = (List<String>) imgMap.get("min");
		return imgList;
	}
	
	private static String splitImgMinToBigUrl(String imgSrc){
		if(imgSrc == null)
			return null;
		int indexof = imgSrc.lastIndexOf("_");
		if(indexof > 0){
			imgSrc = imgSrc.substring(0,indexof);
			if(imgSrc.indexOf(".jpg") > 0
					|| imgSrc.indexOf(".png")>0
					|| imgSrc.indexOf(".gif")>0
					|| imgSrc.indexOf(".jpeg")>0
					|| imgSrc.indexOf(".bmp")>0)
				return imgSrc;
		}
		return imgSrc;
	}
	
	@Autowired
	private GoodsInfoDao goodsInfoDao;
	@Autowired
	private GoodsSkuDao goodsSkuDao;
	@Autowired
	private GoodsSkuBof goodsSkuBof;
	@Autowired
	private GoodsAttrValDao goodsAttrValDao;
	@Autowired
	private AttributesService attributesService;
	
}
